package com.syqc.custom

import android.annotation.SuppressLint
import android.content.Context
import android.content.res.TypedArray
import android.graphics.drawable.ColorDrawable
import android.util.AttributeSet
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.view.WindowManager
import android.widget.FrameLayout
import android.widget.PopupWindow
import androidx.core.content.ContextCompat
import androidx.core.view.isVisible
import androidx.recyclerview.widget.LinearLayoutManager
import com.chad.library.adapter.base.BaseQuickAdapter
import com.chad.library.adapter.base.viewholder.BaseViewHolder
import com.syqc.choose.car.TypePopup
import com.syqc.comlib.rx.doAfterChanged
import com.syqc.comlib.utils.CacheMMKV
import com.syqc.comlib.utils.MLog
import com.syqc.comlib.utils.sub
import com.syqc.comlib.utils.subPlate
import com.syqc.comlib.utils.toast
import com.syqc.entity.CarLick
import com.syqc.monitor.R
import com.syqc.monitor.databinding.CustomEditBinding
import com.syqc.monitor.databinding.PopupSearchRecyclerBinding
import com.syqc.utils.ChooseCars
import com.syqc.net.Net
import com.syqc.net.ServiceHelper
import io.reactivex.rxjava3.disposables.Disposable


/**
 *@Author Jasper
 *@Time   2020/11/2
 *@Desc  自定义搜索车辆
 */
class SearchCarEditText : FrameLayout {
    var isChoose = false
    private var textLength = 0

    constructor(context: Context) : super(context) {
        initView(context, null)
    }

    constructor(context: Context, attrs: AttributeSet?) : super(context, attrs) {
        initView(context, attrs)
    }

    constructor(context: Context, attrs: AttributeSet?, defStyle: Int) : super(
        context,
        attrs,
        defStyle
    ) {
        initView(context, attrs)
    }

    private lateinit var binding: CustomEditBinding

    //是否首次进入
    private var isFirst = true

    //是否赋值
    private var isSetText = false

    //搜素车辆条件  1 车牌   2.终端号  3 SIM 卡   4.终端标识
    private var type = 0

    //是否历史数据
    private var isHistory = true

    /** Is car login */
    var isShowChoose = false
    private var typeStr = ArrayList<String>()
    private var hintStr = ArrayList<String>()
    private val mTypePopup by lazy {
        TypePopup(context) {
            type = it
            binding.tvSearchType.text = typeStr[it]
            binding.editCustomSearch.hint = hintStr[it]
        }
    }

    private fun initView(context: Context, attrs: AttributeSet?) {

        typeStr.clear()
        typeStr.add(context.getString(R.string.desc_car_plate_new))
        typeStr.add(context.getString(R.string.desc_tmn_num))
        typeStr.add(context.getString(R.string.desc_sim_num))
        typeStr.add(context.getString(R.string.desc_tmn_logo))
        mTypePopup.setData(typeStr)

        hintStr.clear()
        hintStr.add(context.getString(R.string.hint_search_car_plate))
        hintStr.add(context.getString(R.string.hint_search_car_tmn))
        hintStr.add(context.getString(R.string.hint_search_car_sim))
        hintStr.add(context.getString(R.string.hint_search_car_logo))


        ChooseCars.initData()
        binding = CustomEditBinding.inflate(LayoutInflater.from(context), this, true)
        val typedArray: TypedArray =
            context.obtainStyledAttributes(attrs, R.styleable.custom_edit)
        val hint = typedArray.getString(R.styleable.custom_edit_custom_hint)
        binding.editCustomSearch.hint = hint
        binding.editCustomSearch.setTextColor(
            ContextCompat.getColor(
                context,
                R.color.color_F69
            )
        )
        initEvent()
        binding.editCustomSearch.setText("")
        typedArray.recycle()
    }

    fun initEvent() {
        binding.ivCustomDelete.setOnClickListener {
            isChoose = false
            isSetText = false
            dismiss()
            binding.editCustomSearch.setTextColor(
                ContextCompat.getColor(
                    context,
                    R.color.color_F69
                )
            )
            binding.editCustomSearch.setText("")
            it.visibility = View.INVISIBLE
        }

        binding.tvSearchType.setOnClickListener {
            mTypePopup.show(binding.tvSearchType, type)
        }
        binding.editCustomSearch.doAfterChanged {
            MLog.e("***********************************$isSetText    $isChoose   $isHistory")
            if (it.isEmpty() && !isSetText) {
                if (isFirst) {
                    isFirst = false
                    if (isShowChoose) {
                        binding.ivCustomDelete.visibility = View.INVISIBLE
                        return@doAfterChanged
                    }

                    val list = ChooseCars.getLickCars()
                    if (list.isNotEmpty()) {
                        entity = list[0]
                        if (isHistory) {
                            handleLast()
                        } else {
                            handleInfo()
                        }
                    } else {
                        binding.editCustomSearch.postDelayed({
                            mInputPopup.showLogo(true)
                            mInputPopup.showAsDropDown(binding.llEdit)
                            isHistory = true
                            mInputPopup.setList(ChooseCars.getLickCars())
                        }, 200)
                    }


                } else {
                    binding.editCustomSearch.postDelayed({
                        mInputPopup.showLogo(true)
                        mInputPopup.showAsDropDown(binding.llEdit)
                        isHistory = true
                        mInputPopup.setList(ChooseCars.getLickCars())
                    }, 300)
                }
                return@doAfterChanged
            }
            mInputPopup.showLogo(false)
            if (it.length < textLength) {
                isSetText = false
                binding.editCustomSearch.setTextColor(
                    ContextCompat.getColor(
                        context,
                        R.color.color_F69
                    )
                )
                isChoose = false
            }
            MLog.e("***********************************$isSetText    $isChoose   $isHistory")
            if (it.isNotEmpty()) {
                if (isShowDelete) {
                    binding.ivCustomDelete.isVisible = true
                }
                if (!isChoose) {
                    binding.editCustomSearch.postDelayed({
                        mInputPopup.showAsDropDown(binding.llEdit)
                        searchCar(it)
                    }, 300)
                }
            } else {
                isChoose = false
                binding.ivCustomDelete.visibility = View.INVISIBLE
                dismiss()
            }
        }
    }

    private fun dismiss() {
        mInputPopup?.let {
            if (it.isShowing) it.dismiss()
        }
    }

    private var subscribe: Disposable? = null
    private fun searchCar(plate: String) {
        subscribe?.dispose()
        subscribe =
            ServiceHelper.getRepository().getSearchCar(plate, "${type + 1}", false).subscribe({
                if (it.isEmpty()) {
                    R.string.toast_query_no_car.toast(context)
                    mInputPopup.setList(it)
                    isHistory = false
                } else {
                    isHistory = false
                    mInputPopup.setList(it)
                }
            }, {
                R.string.toast_query_no_car.toast(context)
                dismiss()
            })
    }

    private val mInputPopup by lazy {
        InputPopup(context, binding.llEdit.measuredWidth) {
            entity = it
            if (isHistory) {
                getVerify(entity!!.carId)
            } else {
                handleInfo()
            }
        }
    }
    private var entity: CarLick? = null

    fun setText(title: String) {
        isSetText = true
        isChoose = true
        textLength = title.length
        binding.editCustomSearch.setTextColor(
            ContextCompat.getColor(
                context,
                R.color.color_28C
            )
        )
        binding.editCustomSearch.setText(subPlate(title, 14))
        binding.editCustomSearch.setSelection(binding.editCustomSearch.text.length)
    }

    //是否显示delete图标
    private var isShowDelete = true
    fun setEnable(isEnable: Boolean) {
        binding.editCustomSearch.isEnabled = isEnable
        binding.tvSearchType.isEnabled = isEnable
        isShowDelete = false
    }

    private var carIdBack: OnCarIdBack? = null
    fun setOnCarIdBack(carIdBack: OnCarIdBack) {
        this.carIdBack = carIdBack
    }

    interface OnCarIdBack {
        fun back(entity: CarLick)
    }


    private class EditAdapter :
        BaseQuickAdapter<CarLick, BaseViewHolder>(R.layout.item_search_edit) {
        override fun convert(holder: BaseViewHolder, item: CarLick) {
            holder.setText(R.id.tv_search_edit, sub("${item.carPlate}[${item.carName}]", 20))
        }
    }

    @SuppressLint("CheckResult")
    private fun getCarInfo(carId: String) {
        ServiceHelper.getRepository().getCarInfo(carId).compose(Net.applySingleSchedulers())
            .subscribe({
                it.run {
                    setText(subPlate(carPlate))
                    carIdBack?.back(CarLick(carId, carName, carPlate, iconLink, videos))
                    mInputPopup?.dismiss()
                    //添加
                    ChooseCars.addCars(
                        carId = carId,
                        carPlate = carPlate,
                        carName = carName,
                        videos = videos,
                        iconLink = iconLink,
                        isVideo = !videos.isNullOrEmpty()
                    )

                }
            }, {
                handleInfo()
            })
    }

    /**
     * 查询是否有当前车辆权限
     *
     * @param carId
     */
    private fun getVerify(carId: String) {
        ServiceHelper.getRepository().getVerify(carId).compose(Net.applySingleSchedulers())
            .subscribe({
                if (it == "true") {
                    getCarInfo(carId)
                } else {
                    context.toast(context.getString(R.string.toast_no_verify))
                }
            }, {
                getCarInfo(carId)
            })
    }

    private fun handleLast() {
        val carId = CacheMMKV.decodeString("last_carId", "")
        if (carId.isNotEmpty()) {
            getVerify(carId)
        }
    }

    private fun handleInfo() {
        entity?.run {
            setText(subPlate(carPlate))
            carIdBack?.back(this)
            mInputPopup?.dismiss()
            //添加
            ChooseCars.addCars(
                carId = carId,
                carPlate = carPlate,
                carName = carName,
                videos = videos,
                iconLink = iconLink,
                isVideo = !videos.isNullOrEmpty()
            )
        }
    }

}

class InputPopup(
    private val context: Context,
    private val widthView: Int,
    val callback: (CarLick) -> Unit
) : PopupWindow() {
    private val mAdapter by lazy { EditAdapter() }
    val binding = PopupSearchRecyclerBinding.inflate(LayoutInflater.from(context))

    init {
        contentView = binding.root
        isClippingEnabled = false
        width = widthView
        height = ViewGroup.LayoutParams.WRAP_CONTENT
        isOutsideTouchable = true
        inputMethodMode = PopupWindow.INPUT_METHOD_NEEDED
        softInputMode = WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE;
        setBackgroundDrawable(ColorDrawable(0xFFFFFFFF.toInt()))

        binding.recyclerView.layoutManager = LinearLayoutManager(context)
        binding.recyclerView.adapter = mAdapter

        mAdapter.setOnItemClickListener { adapter, view, position ->
            callback(adapter.data[position] as CarLick)
        }
    }

    fun setList(list: MutableList<CarLick>) {
        mAdapter.setList(list)
    }

    fun showLogo(isVisible: Boolean) {
        binding.tvSearchLogo.isVisible = isVisible
    }
}

class EditAdapter :
    BaseQuickAdapter<CarLick, BaseViewHolder>(R.layout.item_search_edit) {
    override fun convert(holder: BaseViewHolder, item: CarLick) {
        holder.setText(R.id.tv_search_edit, sub("${item.carPlate}[${item.carName}]", 20))
    }
}